var http = require('http');


var https = require('https');
var querystring = require('querystring');

var datatable = {
    get: {}
};
var URL = require('url').URL;
var POST = function (url, data, Callback) {
    var obj = new URL(url);
    var ccv = http;
    if (obj.protocol == "https:") {
        ccv = https;
    }
    var content = querystring.stringify(data);
    var options = {
        hostname: obj.hostname,
        port: obj.port,
        path: obj.pathname,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    };
    var value = "";

    var req = ccv.request(options, function (res) {

        var value = "";
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            value = value + chunk;
        });
        res.on('end', function () {
            Callback(value)
        });
    });
    req.on('error', function (e) {
        Callback(null, e)
    });
    req.write(content);
    req.end();
}
var GET = function (url, data, Callback) {

    var obj = new URL(url);

    var ccv = http;
    if (obj.protocol == "https:") {

        ccv = https;

    }


    var content = querystring.stringify(data);

    var options = {
        hostname: obj.hostname,
        port: obj.port,
        path: obj.pathname + (content == "" ? "" : '?' + content),
        method: 'GET'
    };
    var key = url + (content == "" ? "" : '?' + content);
    var req = ccv.request(options, function (res) {

        var lastModified = new Date(res.headers["last-modified"]);
        lastModified = lastModified.getTime();
        if (datatable.get[key] && datatable.get[key].lastModified > lastModified) {
            Callback(datatable.get[key].value)
        } else {
            var value = "";
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                value = value + chunk;
            });
            res.on('end', function () {
                var lastModified = new Date();
                lastModified = lastModified.getTime();
                datatable.get[key] = {
                    value: value,
                    lastModified: lastModified
                };
                Callback(value)
            });
        }
    });

    req.on('error', function (e) {
        if (datatable.get[key]) {
            Callback(datatable.get[key].value)
        } else {
            Callback(null, e)
        }
    });
    req.end();
}
module.exports = {
    POST: POST,
    GET: GET,
}